package com.smart.auth.controller;

import cn.hutool.json.JSONObject;

import com.smart.auth.util.RequestUtils;
import com.smart.common.constant.AuthConstants;
import com.smart.common.result.BaseResult;
import com.smart.redis.service.RedisService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/oauth")
@AllArgsConstructor
@Slf4j
public class LogoutController {

    @Resource
    RedisService redisService;

    @DeleteMapping("/logout")
    public BaseResult logout() {
        JSONObject jsonObject = RequestUtils.getJwtPayload();
        // JWT唯一标识
        String jti = jsonObject.getStr(AuthConstants.JWT_JTI);
        // JWT过期时间戳
        long exp = jsonObject.getLong(AuthConstants.JWT_EXP);
        long currentTimeSeconds = System.currentTimeMillis() / 1000;
        if (exp < currentTimeSeconds) {
            // token已过期，无需加入黑名单
            return BaseResult.success();
        }
        redisService.setEx(AuthConstants.TOKEN_BLACKLIST_PREFIX + jti, null, (exp - currentTimeSeconds), TimeUnit.SECONDS);
        return BaseResult.success();
    }

}
